<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>修改存储空间</title>
    <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style type="text/tailwindcss">
        @layer utilities {
            .form-input {
                @apply w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200;
            }
            .form-label {
                @apply block text-sm font-medium text-gray-700 mb-1;
            }
            .form-group {
                @apply mb-4;
            }
            .error-message {
                @apply text-red-500 text-sm mt-1;
            }
            .radio-group {
                @apply flex items-center space-x-4;
            }
            .radio-option {
                @apply flex items-center;
            }
            .radio-input {
                @apply w-4 h-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded;
            }
            .radio-label {
                @apply ml-2 text-sm font-medium text-gray-700;
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航 -->
<header class="bg-white shadow-sm sticky top-0 z-10">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cloud text-blue-600 text-xl"></i>
            <h1 class="text-lg font-semibold text-gray-800">云存储空间管理</h1>
        </div>
        <nav>
            <ul class="flex space-x-6">
                <li><a href="OssServlet?method=list" class="text-gray-600 hover:text-blue-600 transition">存储空间列表</a></li>
                <li><a href="#" class="text-gray-600 hover:text-blue-600 transition">使用统计</a></li>
                <li><a href="#" class="text-gray-600 hover:text-blue-600 transition">帮助文档</a></li>
            </ul>
        </nav>
    </div>
</header>

<!-- 主要内容 -->
<main class="flex-1 container mx-auto px-4 py-8">
    <div class="max-w-2xl mx-auto bg-white rounded-xl shadow-md overflow-hidden border border-gray-200">
        <div class="bg-blue-600 text-white p-4">
            <h2 class="text-xl font-bold flex items-center">
                <i class="fa fa-pencil-square-o mr-2"></i>修改存储空间
            </h2>
            <p class="text-sm mt-1 opacity-90">修改存储空间的基本信息和配置</p>
        </div>

        <div class="p-6">
            <form id="ossForm" method="post" enctype="multipart/form-data">
                <input type="hidden" name="id" value="${oss.id}">
                <input type="hidden" name="pageNo" value="${param.pageNo}">
                <input type="hidden" name="method" value="saveOrUpdate">

                <div class="form-group" style="display: none;">
                    <label for="bucketId" class="form-label">存储空间ID</label>
                    <input id="bucketId" value="${oss.id}" type="text" class="form-input bg-gray-100" readonly>
                </div>

                <div class="form-group">
                    <label for="bucketName" class="form-label">存储空间名称</label>
                    <div class="relative">
                        <input id="bucketName" value="${oss.name}" name="bucketName" type="text" class="form-input" maxlength="63">
                        <div id="bucketNameLength" class="absolute right-3 top-2 text-xs text-gray-400">
                            <span id="currentLength">0</span>/63
                        </div>
                    </div>
                    <div id="bucketNameError" class="error-message"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">存储类型</label>
                    <div class="radio-group">
                        <label class="radio-option">
                            <input type="radio" name="type" value="标准存储"
                            ${oss.type eq '标准存储' ? 'checked' : ''} class="radio-input">
                            <span class="radio-label">标准存储</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="type" value="低频访问存储"
                            ${oss.type eq '低频访问存储' ? 'checked' : ''} class="radio-input">
                            <span class="radio-label">低频访问存储</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="type" value="归档存储"
                            ${oss.type eq '归档存储' ? 'checked' : ''} class="radio-input">
                            <span class="radio-label">归档存储</span>
                        </label>
                    </div>
                    <div id="typeError" class="error-message"></div>
                </div>

                <div class="form-group">
                    <label class="form-label">访问权限</label>
                    <div class="radio-group">
                        <label class="radio-option">
                            <input type="radio" name="permission" value="私有(Pr)" ${oss.permission == '私有(Pr)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">私有(Pr)</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="permission" value="公共读(R)" ${oss.permission == '公共读(R)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">公共读(R)</span>
                        </label>
                        <label class="radio-option">
                            <input type="radio" name="permission" value="公共读写(RW)" ${oss.permission == '公共读写(RW)'? 'checked' : ''} class="radio-input">
                            <span class="radio-label">公共读写(RW)</span>
                        </label>
                    </div>
                    <div id="permissionError" class="error-message"></div>
                </div>


                <div class="flex justify-end space-x-3 mt-6">
                    <button type="button" onclick="history.back()" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition duration-200 flex items-center">
                        <i class="fa fa-arrow-left mr-1"></i> 返回
                    </button>
                    <button type="submit" id="submitBtn" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg shadow-md transition-all duration-200 flex items-center gap-2 transform hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                        <i class="fa fa-check-circle"></i> 提交修改
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-gray-800 text-white py-4">
    <div class="container mx-auto px-4 text-center">
        <p>© 2025 云存储空间管理系统 | 版权所有</p>
    </div>
</footer>

<!-- JavaScript 逻辑 -->
<script src="static/script/jquery-1.7.2.js"></script>
<script>
    $(document).ready(function() {
        // 从URL获取ID参数
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return decodeURIComponent(r[2]);
            return null;
        }

        // 加载存储空间数据
        function loadOssData(id) {
            if (!id) return;

            $.ajax({
                url: "OssServlet",
                type: "GET",
                data: {
                    method: "getOss",
                    id: id
                },
                dataType: "json",
                success: function(response) {
                    console.log("加载数据成功:", response);
                    if (response.data) {
                        renderOssData(response.data);
                    } else {
                        console.error("加载数据失败:", response.message);
                        alert("加载存储空间数据失败: " + (response.message || "未知错误"));
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("AJAX请求失败:", textStatus, errorThrown);
                    alert("网络错误，请刷新页面重试");
                }
            });
        }

        // 渲染数据到表单
        function renderOssData(oss) {
            // 基础信息
            $("#bucketId").val(oss.id);
            $("input[name='id']").val(oss.id);
            $("#bucketName").val(oss.name);

            // 更新长度计数器
            updateLengthCounter();

            // 设置存储类型
            $("input[name='type'][value='" + oss.type + "']").prop("checked", true);

            // 设置访问权限
            $("input[name='permission'][value='" + oss.permission + "']").prop("checked", true);


        }

        // 表单提交处理
        $("#ossForm").on("submit", function(e) {
            e.preventDefault();

            // 验证表单数据
            var isValid = true;
            var bucketName = $("input[name='bucketName']").val().trim();

            // 重置所有错误消息
            $(".error-message").text("");

            // 验证存储空间名称
            if (!bucketName) {
                $("#bucketNameError").text("存储空间名称不能为空");
                isValid = false;
            } else if (bucketName.length > 63) {
                $("#bucketNameError").text("存储空间名称不能超过63个字符");
                isValid = false;
            }

            // 验证存储类型
            if (!$("input[name='type']:checked").val()) {
                $("#typeError").text("请选择存储类型");
                isValid = false;
            }

            // 验证访问权限
            if (!$("input[name='permission']:checked").val()) {
                $("#permissionError").text("请选择访问权限");
                isValid = false;
            }

            if (!isValid) {
                return false;
            }

            // 准备表单数据
            var formData = new FormData(this);

            // 提交表单
            $.ajax({
                url: "OssServlet?method=saveOrUpdate",
                type: "POST",
                data: formData,
                contentType: false,
                processData: false,
                beforeSend: function() {
                    $("#submitBtn").prop("disabled", true).html('<i class="fa fa-spinner fa-spin"></i> 提交中...');
                },
                success: function(response) {
                    if (response.success) {
                        // 显示成功通知
                        showNotification("修改成功", "success");
                        setTimeout(() => {
                            window.location.href = "${pageContext.request.contextPath}/index.jsp";
                        }, 2000);
                    } else {
                        showNotification(response.message || "名称重复", "error");
                        $("#submitBtn").prop("disabled", false).html('<i class="fa fa-check-circle"></i> 提交修改');
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("AJAX请求失败:", textStatus, errorThrown);
                    showNotification("网络错误，请重试", "error");
                    $("#submitBtn").prop("disabled", false).html('<i class="fa fa-check-circle"></i> 提交修改');
                }
            });
        });

        // 显示通知
        function showNotification(message, type) {
            console.log(message)
            var notification = $("<div>")
                .addClass("fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full")
                .addClass(type === "success" ? "bg-green-500 text-white" : "bg-red-500 text-white");

            // 创建图标元素
            var icon = $("<i>")
                .addClass(`fa ${type == "success" ? "fa-check-circle" : "fa-exclamation-circle"} mr-2`);

            // 将图标和消息文本添加到通知中
            notification.append(icon).append(document.createTextNode(message));
            $("body").append(notification);

            // 显示通知
            setTimeout(() => {
                notification.removeClass("translate-x-full");
            }, 10);

            // 自动关闭
            setTimeout(() => {
                notification.addClass("translate-x-full");
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }

        // 初始化长度计数器
        updateLengthCounter();

        // 监听输入事件
        $("input[name='bucketName']").on("input", function() {
            updateLengthCounter();
        });

        // 页面加载时获取数据
        var ossId = getUrlParam("id") || "${param.id}";
        if (ossId) {
            loadOssData(ossId);
        } else {
            console.warn("未找到存储空间ID参数");
        }
    });

    // 更新长度计数器
    function updateLengthCounter() {
        var input = $("input[name='bucketName']");
        var value = input.val();
        var length = getBytesLength(value);

        $("#currentLength").text(length);

        if (length > 63) {
            var maxChars = 0;
            var byteCount = 0;

            while (byteCount <= 63 && maxChars < value.length) {
                var code = value.charCodeAt(maxChars);
                byteCount += code > 255 ? 2 : 1;
                if (byteCount <= 63) maxChars++;
            }

            input.val(value.substring(0, maxChars));
            updateLengthCounter();
        }
    }

    // 计算字符串字节长度
    function getBytesLength(str) {
        return encodeURIComponent(str).replace(/%../g, 'x').length;
    }

    // 显示通知
    function showNotification(message, type) {
        var notification = $("<div>")
            .addClass("fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transform transition-all duration-300 translate-x-full")
            .addClass(type === "success" ? "bg-green-500 text-white" : "bg-red-500 text-white");

        var icon = $("<i>")
            .addClass(`fa ${type == "success" ? "fa-check-circle" : "fa-exclamation-circle"} mr-2`);

        notification.append(icon).append(document.createTextNode(message));
        $("body").append(notification);

        setTimeout(() => {
            notification.removeClass("translate-x-full");
        }, 10);

        setTimeout(() => {
            notification.addClass("translate-x-full");
            setTimeout(() => {
                notification.remove();
            }, 300);
        }, 3000);
    }
</script>
</body>
</html>